import pandas as pd
import mplfinance as mpf
import okx.MarketData as MarketData


flag = "0"
marketDataAPI =  MarketData.MarketAPI(flag=flag)
result = marketDataAPI.get_candlesticks(instId="BTC-USDT",bar = '1H')
raw_data = result["data"]

df = pd.DataFrame(raw_data, columns=[
    'timestamp', 'open', 'high', 'low', 'close', 'vol', 'volCcy', 'volCcyQuote', 'confirm'
])

df['Date'] = pd.to_datetime(df['timestamp'].astype(int), unit='ms')
df.set_index('Date', inplace=True)

for col in ['open', 'high', 'low', 'close', 'vol', 'volCcy', 'volCcyQuote']:
    df[col] = df[col].astype(float)

df.rename(columns={
    'open': 'Open',
    'high': 'High',
    'low': 'Low',
    'close': 'Close',
    'vol': 'Volume'
}, inplace=True)

df = df.sort_index()

# 保存K线图到本地
mpf.plot(
    df, 
    type='candle', 
    volume=True, 
    style='charles', 
    title='Crypto Kline', 
    ylabel='Price', 
    savefig='crypto_kline.png'
)

print('K线图已保存为 crypto_kline.png')
